<?php

/**
 * 验证手机号格式
 *
 * @param $str
 * @return bool
 */
function is_mobile($str)
{
    return (!preg_match("/^1[3|4|5|6|7|8|9]{1}[0-9]{9}$/",$str)) ? FALSE : TRUE;
}

/**
 * curl公用方法
 *
 * @param $url            请求地址
 * @param array $params   参数
 * @param string $type    返回类型
 * @param string $method  请求方法
 * @param int $timeout    超时时间
 * @param array $headers  请求头部
 * @return array|mixed
 */
function get_url($url = '', $params = array(), $type='JSON', $method='POST', $timeout = 30, $headers = array())
{
    if(is_array($params)) {
        $params = http_build_query($params);
    }

    $curl = curl_init();//初始化curl

    if ('get' == $method) {
        $pos = strpos($url, "?");

        if($pos === false) {
            $request_url = $url."?".$params;
        } else {
            $request_url = $url."&".$params;
        }
        curl_setopt($curl, CURLOPT_URL, $request_url);
    } else {
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);//设置传送的参数
    }

    if ($headers) {
        curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);
    }

    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    for($i=0 ;$i < 5; $i++) {
        $res = curl_exec($curl);
        $err = curl_error($curl);

        if(empty($err)) {
            break;
        }
    }

    if (false === $res || !empty($err)) {
        $errno = curl_errno($curl);
        $Info = curl_getinfo($curl);
        curl_close($curl);

        return array(
            'status' => 250,
            'errno' => $errno,
            'msg' => $err,
            'data' => $Info,
        );
    }

    curl_close($curl);

    if ('JSON' == $type) {
        $res = json_decode($res,true);
    }

    return $res;
}

/**
 * @param $url 请求网址
 * @param bool $params 请求参数
 * @param int $ispost 请求方式
 * @param int $https https协议
 * @return bool|mixed
 */
function curl($url, $params = false, $ispost = 0, $https = 0)
{
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($https) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
    }
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            if (is_array($params)) {
                $params = http_build_query($params);
            }
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }

    $response = curl_exec($ch);

    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}

/**
 * 发送短信
 *
 * @param $mobile
 * @param $content
 * @return mixed
 */
function sms($mobile, $content)
{
    $sign = '【校朋-激励教育平台】';
    $url  = "https://dx.ipyy.net/sms.aspx";

    $body = [
        'action'=>'send',
        'userid'=>'',
        'account'=>'AF00002',
        'password'=>'AF0000233',
        'mobile'=>$mobile,
        'extno'=>'',
        'content'=>$sign . $content,
        'sendtime'=>'',
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

/**
 * @param $time_type 1今天 2昨天 3本周 4上周 5近7天 6本月 7上月 8近30天 9本季度 10上季度 11本年 12上年
 * @param bool $timestamp_flag
 * @return array
 */
function get_time($time_type, $timestamp_flag = false)
{
    date_default_timezone_set('PRC');
    switch ($time_type){
        case '1':
            //今天
            $start_time = $timestamp_flag ? strtotime(date("Y-m-d 00:00:00")) : date("Y-m-d 00:00:00");
            $end_time   = $timestamp_flag ? time() : date("Y-m-d H:i:s");
            break;
        case '2':
            //昨天
            $start_time = $timestamp_flag ? strtotime(date("Y-m-d 00:00:00")) - 86400 : date('Y-m-d 00:00:00', strtotime('-1 day'));
            $end_time   = $timestamp_flag ? strtotime(date("Y-m-d 00:00:00")) - 1 : date('Y-m-d 23:59:59', strtotime('-1 day'));
            break;
        case '3':
            //本周
            $start_time = $timestamp_flag ? mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")) : date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
            $end_time   = $timestamp_flag ? time() : date("Y-m-d H:i:s");
            //$end_time   = $timestamp_flag ? mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")) : date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
            break;
        case '4':
            //上周
            $start_time = $timestamp_flag ? mktime(0,0,0, date('m'),date('d') - date('w') + 1 - 7, date('Y')) : date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y")));
            $end_time   = $timestamp_flag ? mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y")) : date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y")));
            break;
        case '5':
            //近7天
            $start_time = $timestamp_flag ? strtotime('-7 day') : date('Y-m-d H:i:s', strtotime('-7 day'));
            $end_time   = $timestamp_flag ? time() : date("Y-m-d H:i:s");
            break;
        case '6':
            //本月
            $start_time = $timestamp_flag ? strtotime(date("Y-m-01 00:00:00",time())) : date("Y-m-01 00:00:00",time());
            $end_time   = $timestamp_flag ? time() : date("Y-m-d H:i:s");
            //$end_time   = $timestamp_flag ? strtotime(date("Y-m-t 23:59:59")) : date("Y-m-t 23:59:59");
            //$end_time   = $timestamp_flag ? mktime(23,59,59,date("m"),date("t"),date("Y")) : date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
            break;
        case '7':
            //上月
            //$start_time = $timestamp_flag ? mktime(0, 0 , 0,date("m")-1,1,date("Y")) : date("Y-m-d H:i:s", mktime(0, 0 , 0,date("m")-1,1,date("Y")));
            //$end_time   = $timestamp_flag ? mktime(23,59,59,date("m") ,0,date("Y")) : date("Y-m-d H:i:s", mktime(23,59,59,date("m") ,0,date("Y")));
            $start_time = $timestamp_flag ? strtotime(date("Y-m-01 00:00:00",strtotime("-1 month"))) : date("Y-m-01 00:00:00",strtotime("-1 month"));
            $end_time   = $timestamp_flag ? strtotime(date("Y-m-t 23:59:59",strtotime("-1 month"))) : date("Y-m-t 23:59:59",strtotime("-1 month"));
            break;
        case '8':
            //近30天
            $start_time = $timestamp_flag ? strtotime('-30 day') : date('Y-m-d H:i:s', strtotime('-30 day'));
            $end_time   = $timestamp_flag ? time() : date("Y-m-d H:i:s");
            break;
        case '9':
            //本季度
            $season     = ceil(date("n") /3); //获取月份的季度
            $start_time = $timestamp_flag ? mktime(0,0,0,($season - 1) *3 +1,1,date('Y')) : date('Y-m-01 H:i:s',mktime(0,0,0,($season - 1) *3 +1,1,date('Y')));
            $end_time   = $timestamp_flag ? mktime(23,59,59,$season * 3,1,date('Y')) : date('Y-m-t H:i:s',mktime(23,59,59,$season * 3,1,date('Y')));
            break;
        case '10':
            //上季度
            $season     = ceil(date("n") /3); //获取月份的季度
            $start_time = $timestamp_flag ? mktime(0,0,0,($season - 2) * 3 +1,1,date('Y')) : date('Y-m-01 H:i:s',mktime(0,0,0,($season - 2) * 3 +1,1,date('Y')));
            $end_time   = $timestamp_flag ? mktime(23,59,59,($season - 1) * 3,1,date('Y')) : date('Y-m-t H:i:s',mktime(23,59,59,($season - 1) * 3,1,date('Y')));
            break;
        case '11':
            //本年
            $start_time = $timestamp_flag ? strtotime(date('Y-01-01 00:00:00')) : date('Y-01-01 00:00:00');
            $end_time   = $timestamp_flag ? strtotime(date('Y-12-31 23:59:59')) : date('Y-12-31 23:59:59');
            break;
        case '12':
            //上年
            $start_time = $timestamp_flag ? strtotime(date('Y-01-01 00:00:00',strtotime('-1 year'))) : date('Y-01-01 00:00:00',strtotime('-1 year'));
            $end_time   = $timestamp_flag ? strtotime(date('Y-12-31 23:59:59',strtotime('-1 year'))) : date('Y-12-31 23:59:59',strtotime('-1 year'));
            break;
        default :
            //默认今天
            $start_time = $timestamp_flag ? strtotime(date("Y-m-d 00:00:00")) : date("Y-m-d 00:00:00");
            $end_time   = $timestamp_flag ? time() : date("Y-m-d H:i:s");
            break;
    }

    return [
        'start_time' => $start_time,
        'end_time' => $end_time,
    ];


}

/**
 * 计算几分钟前、几小时前、几天前的几个函数
 *
 * @param $the_time
 * @return string
 */
function time_tran($the_time)
{
    $now_time = date("Y-m-d H:i:s", time() + 8 * 60 * 60);
    $now_time = strtotime($now_time);
    $show_time = strtotime($the_time);
    $dur = $now_time - $show_time;
    if ($dur < 0) {
        return $the_time;
    } else {
        if ($dur < 60) {
            return $dur . '秒前';
        } else {
            if ($dur < 3600) {
                return floor($dur / 60) . '分钟前';
            } else {
                if ($dur < 86400) {
                    return floor($dur / 3600) . '小时前';
                } else {
                    if ($dur < 259200) {//3天内
                        return floor($dur / 86400) . '天前';
                    } else {
                        return $the_time;
                    }
                }
            }
        }
    }
}

/**
 * 计算几分钟前、几小时前、几天前的几个函数
 *
 * @param $time
 * @return string
 */
function format_date($time)
{
    $t = time() - $time;
    $f = [
        '31536000'=>'年',
        '2592000'=>'个月',
        '604800'=>'星期',
        '86400'=>'天',
        '3600'=>'小时',
        '60'=>'分钟',
        '1'=>'秒'
    ];

    foreach ($f as $k=>$v)    {
        if (0 !=$c=floor($t/(int)$k)) {
            return $c.$v.'前';
        }
    }
}

/**
 * 生成uuid
 *
 * @return string
 */
function uuid()
{
    mt_srand ( ( double ) microtime () * 10000 );
    $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); //根据当前时间（微秒计）生成唯一id.
    $hyphen = chr ( 45 ); // "-"
    $uuid = '' . substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );

    return $uuid;
}

/**
 * 生成唯一标识符
 *
 * @return string
 */
function unique()
{
    return date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 生成唯一id
 */
function guid($factor='',$prefix='',$suffix='')
{
    list($usec, $sec) = explode(" ", microtime());
    $guid = $prefix. $factor. $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']
        . $sec . $usec
        . mt_rand(0,1000000).time(). mt_rand(0,1000000).$suffix;
    $guid = substr(sha1($guid),8,32);
    $guid = base_convert($guid,16,36);
    return $prefix.$guid.$suffix;
}

/**
 * 获取图片
 *
 * @param string $url
 * @return string
 */
function get_img($url = '')
{
    if (!$url)
        return '';

    if (strstr($url, 'http://') || strstr($url, 'https://')) {
        return $url;
    } else if (strstr($url, 'uploads/')) {
        if (strpos($url, '/') == 0) {
            return env('DOMAIN') . $url;
        }
        return env('DOMAIN') . '/' . $url;
    } else {
        return env('QN') . '/' . $url;
    }

}

/**
 * 对提供的数据进行urlsafe的base64编码。
 *
 * @param string $str 待编码的数据，一般为字符串
 * @return string 编码后的字符串
 */
function safe_base64_encode($str)
{
    return str_replace(array('+','/','='), array('-','_',''), base64_encode($str));
}

/**
 * 对提供的urlsafe的base64编码的数据进行解码
 *
 * @param string $str 待解码的数据，一般为字符串
 * @return string 解码后的字符串
 */
function safe_base64_decode($str)
{
    $str  = str_replace(array('-','_'),array('+','/'), $str);
    $mod4 = strlen($str) % 4;
    if ($mod4)
        $str .= substr('====', $mod4);

    return base64_decode($str);
}
